<!-- 新建实物奖品 -->
<template>
  <a-drawer v-model:visible="vdata.visible"  :maskClosable="false" width="40%">
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span v-if="vdata.isAdd">新增广告</span>
        <span v-else>修改广告</span>
      </div>
    </template>
    <a-form
      ref="formRef"
      :model="vdata.saveObject"
      layout="vertical"
      labelAlign="left"
      :rules="vdata.rules"
      :colon="false"
      :wrapper-col="{ span: 22 }"
      style="margin-top: 30px; margin-left: 20px"
    >
      <a-row>
        <a-col :span="12">
          <a-form-item label="机构" name="agentNo">
            <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo']"/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="活动" name="activityId" >
            <a-select
              v-model:value="vdata.saveObject['activityId']"
              :disabled="vdata.activityList.length == 0"
              placeholder="请选择活动"
              :field-names="{ label: 'activityName', value: 'activityId' }"
              :options="vdata.activityList"
            />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="广告内容" name="richText" :wrapper-col="{ span: 23 }">
            <div v-if="vdata.visible" id="editor-container" style="border: 1px solid #ccc">
              <Toolbar
                :editorId="editorId"
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="'simple'"
              />
              <Editor
                :editorId="editorId"
                style="height: 500px; overflow-y: hidden;"
                :defaultHtml="vdata.saveObject.richText"
                :defaultConfig="editorConfig"
                :mode="'simple'"
                @onCreated="handleCreated"
              />
            </div>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-btn-center">
      <a-button :style="{ marginRight: '8px' }" style="margin-right: 8px" @click="()=>{vdata.visible = false}" >
        <close-outlined />
        取消
      </a-button>
      <a-button type="primary" :loading="vdata.btnLoading" @click="handleOkFunc" >
        <check-outlined />
        保存
      </a-button>
    </div>
  </a-drawer>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { IToolbarConfig } from '@wangeditor/editor'
import { Editor, Toolbar, getEditor, removeEditor  } from '@wangeditor/editor-for-vue'
import { req, API_URL_ACTIVITY, API_URL_PAYCASHIERAD_ADD, API_URL_PAYCASHIERAD_DETAIL, API_URL_PAYCASHIERAD_UPDATE } from '@/api/manage'
import { reactive, ref, shallowRef, onBeforeUnmount, defineExpose, getCurrentInstance, watch, onMounted, nextTick } from "vue";
const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties
const formRef = ref();
const gzThreeRef = ref()

const props = defineProps(['callbackFunc'])

const vdata:any = reactive({
  isAdd: false, // 新增OR修改
  visible: false,
  btnLoading: true,
  saveObject: {},
  rules: {
    agentNo: [{ required: true, message: "机构不能为空", trigger: "blur" },],
    activityId: [{ required: true, message: "请选择活动", trigger: "blur" },],
    richText: [
      {
        trigger: "blur",
        required: true,
        validator: () => {
          const editor:any = getEditor(editorId)
          if(!editor.getText().trim()){
            return Promise.reject("广告内容不能为空")
          }else{
            return Promise.resolve()
          }
        }
      }
    ],
  },
  activityList: [], // 活动列表
});

/**
 * 传入机构号，获取活动列表
 * @param agentNo {String} 机构号
 * @param state {Number} 活动状态 默认4 已上线
 */
async function getActivityList(agentNo,state = 4){
  if(agentNo){
    return req.list(API_URL_ACTIVITY,{ agentNo, state }).then(({ records }) => {
      vdata.activityList = records
      if(records.length === 0){
        vdata.saveObject.activityId = void 0
      }
    })
  }
}
/**
 * 监听agentNo的值，来请求活动列表
 */
watch(()=>vdata.saveObject.agentNo,(newV,oldV)=>{
  // 请求活动列表
  getActivityList(newV)
  // 清空选中活动
  if(vdata.isAdd){
    vdata.saveObject.activityId = void 0
  }
},{ immediate: false })

/**
 * 富文本相关数据
 */
// 定义一个编辑器 id ，要求：全局唯一且不变！！！
const editorId = 'wangeEditor-1' // 富文本编辑器
// 编辑器实例
const editorRef = shallowRef()
// 工具栏配置
const toolbarConfig: Partial<IToolbarConfig> = {
  excludeKeys: ['group-image',"insertVideo",'insertTable'], // 排除某些工具栏
}
// 编辑器配置
const editorConfig:any = { placeholder: '请输入广告内容...' }
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 组件销毁时，及时销毁编辑器
onBeforeUnmount(() => {
  const editor = getEditor(editorId)
  if (editor == null ) return
  // 销毁，并移除 editor
  editor.destroy()
  removeEditor(editorId)
})
/** ----------------------------------------------------------------------- */
/**
 * 工具函数 解析地址参数
 */
function parseQueryString(url) {
  const queryString = url.split('?')[1];
  if (!queryString) return {}; // 如果没有查询字符串，返回空对象

  const queryParams:any = {};
  const pairs = queryString.split('&');

  pairs.forEach(pair => {
    const [key, value] = pair.split('=');
    queryParams[key] = decodeURIComponent(value);
  });

  return queryParams;
}
/**
 * 提交新增OR修改
 */
function handleOkFunc() {
  formRef.value.validate().then(()=>{
    vdata.btnLoading = true;
    const MSG = vdata.isAdd ? "新增成功" : '修改成功'
    const URL = vdata.isAdd ? API_URL_PAYCASHIERAD_ADD : API_URL_PAYCASHIERAD_UPDATE
    req.add(URL,{ ...vdata.saveObject, richText: editorRef.value.getHtml() }).then(()=>{
      $infoBox.message.success(MSG)
      props.callbackFunc()
      vdata.visible = false
    }).finally(()=>{
      vdata.btnLoading = false
    })
  }).catch(()=>{})
}

function show(tPayCashierAdId) {
  vdata.isAdd = !tPayCashierAdId
  // 重置数据
  vdata.btnLoading = false;
  vdata.saveObject = {}
  vdata.activityList = []
  clearFieldValidate()

  if(vdata.isAdd){ // 新增
    vdata.visible = true
  }else{  // 修改
    req.add(API_URL_PAYCASHIERAD_DETAIL,{ tPayCashierAdId }).then(res => {
      // 拿到地址活动id activityId
      const { activityId } = parseQueryString(res.path)
      Object.assign(vdata.saveObject,res,{ activityId: activityId - 0 })
      vdata.visible = true
    })
  }
}
// 清除字段验证
function clearFieldValidate(){
  if (formRef.value !== undefined) {
    formRef.value.clearValidate();
  }
}

defineExpose({
  show,
});
</script>

<style lang="less" scoped>
.rule{
  display: flex;
  align-items: center;
  gap: 20px;
  *{
    flex-shrink: 0;
  }
  &:nth-child(n + 2){
    margin-top: 10px;
  }
}
.cp{
  cursor: pointer;
}
.fz18{
  font-size: 18px;
}
</style>
